package com.yoso.starter.boot.util;

import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 *  ip工具类
 * </p>
 *
 * @author shizejin
 * @version 1.0
 * @date 2023/2/27 10:20
 */
public class IPUtil {
    private static final String UNKNOWN = "unknown";

    public static String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || Objects.equals(ip.trim(), "") || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }

        if (ip == null || Objects.equals(ip.trim(), "") || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }

        if (ip == null || Objects.equals(ip.trim(), "") || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        String[] arr = ip.split(",");
        if (!ObjectUtils.isEmpty(arr) && !"unknown".equalsIgnoreCase(arr[0])) {
            ip = arr[0];
        }
        return ip;
    }


    private static final String HOSTNAME_PATTERN = "^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,}$";
    private static final String IPV4_PATTERN = "^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";

    /**
     * 主机名校验
     * @param hostname 主机名
     * @return boolean
     * @author shizejin
     * @date 2024/05/07 10:03
     */
    public static boolean hostnameValid(String hostname) {
        Pattern pattern = Pattern.compile(HOSTNAME_PATTERN);
        Matcher matcher = pattern.matcher(hostname);
        return matcher.matches();
    }

    /**
     * ipv4 地址校验
     * @param ipv4
     * @return boolean
     * @author shizejin
     * @date 2024/05/07 10:35
     */
    public static boolean ipv4Valid(String ipv4) {
        Pattern pattern = Pattern.compile(IPV4_PATTERN);
        Matcher matcher = pattern.matcher(ipv4);
        return matcher.matches();
    }
}
